//
//  cliqsetAppDelegate.m
//  cliqset
//
//  Created by David Hinson on 2/6/09.
//  Copyright Sumner Systems Management, Inc. 2009. All rights reserved.
//

#import "cliqsetAppDelegate.h"
#import "LoginViewController.h"
#import "Contact.h"
#import "ContactsViewController.h"
#import "FavoritesViewController.h"
#import "HoverView.h"
#import "EditAddressViewController.h"
#import "EditEmailViewController.h"
#import "EditIMViewController.h"
#import "EditURLViewController.h"
#import "EditUserViewController.h"
#import "EditPhoneViewController.h"
#import "EmailTypeViewController.h"
#import "IMTypeViewController.h"
#import "URLTypeViewController.h"
#import "PhoneTypeViewController.h"
#import "AddressTypeViewController.h"
#import "Event.h"
#import "HomeViewController.h"
#import "ProfileDetailViewController.h"
#import "ProfileViewController.h"

@implementation cliqsetAppDelegate

@synthesize window;
@synthesize tabBarController;
@synthesize isAuthenticated;
@synthesize isAuthenticating;
@synthesize isSyncing;
@synthesize loginViewController;

@synthesize splashViewController;

@synthesize loginString;
@synthesize passwordString;
@synthesize authenticationString;
@synthesize userString;

@synthesize favorites;
@synthesize contacts;
@synthesize toEvents;
@synthesize fromEvents;
@synthesize profileEvents;
@synthesize database;
@synthesize cliqset;
@synthesize currentStatus;
@synthesize currentProfile;

@synthesize viewTimer, watchDogTimer, reloadListView, updateContactsFlag, updateFavoritesFlag;

#pragma mark ---- App Start ----

// App has launched, now let's do our initial setup
- (void)applicationDidFinishLaunching:(UIApplication *)application {
		
	self.contacts      = [[NSMutableArray array] init];	
	self.favorites     = [[NSMutableArray array] init];	
	self.toEvents      = [[NSMutableArray array] init];	
	self.fromEvents    = [[NSMutableArray array] init];	
	self.profileEvents = [[NSMutableArray array] init];	
	
	// Allocate Database object
	database	    = [[Database alloc] init];

	// Create database, if needed
	[database createEditableCopyOfDatabaseIfNeeded];
	
	// Add the tab bar controller's current view as a subview of the window
	[window addSubview:tabBarController.view];
	
	// Instantiate cliqset
	self.cliqset = [[Cliqset alloc] init];
	
	self.isAuthenticating = YES;
	
	[self flipSplashToFront];	
	
	// Timer (once a second) used to refresh contact details if a user name changes at some point.
	[self resetTimer];
	viewTimer = [[NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] retain];
	[[NSRunLoop currentRunLoop] addTimer:viewTimer forMode:NSDefaultRunLoopMode];
	
	// Watch Dog Timer (2 minutes = 120 seconds) to see if new events and contacts show up.
	[self resetWatchDogTimer];
	watchDogTimer = [[NSTimer timerWithTimeInterval:120 target:self selector:@selector(watchDogFired:) userInfo:nil repeats:YES] retain];
	[[NSRunLoop currentRunLoop] addTimer:watchDogTimer forMode:NSDefaultRunLoopMode];
	
	// Authenticate user
	[self.cliqset authenticate];
}

// General messages
-(void)addTextToLog:(NSString *)text withCaption:(NSString *)caption {
    UIAlertView* myAlert = [[UIAlertView alloc] initWithTitle:caption message:text delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [myAlert show];
    [myAlert release];    
}

// show Contacts Hover View
-(void)showContactsHoverView:(BOOL)show {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					[self slideContactOut];
					}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactsViewController class]]) {
					ContactsViewController* dref = (ContactsViewController*)f1;
					[dref showHoverView:show];
				}
			}
			break;
		}
	}
}

// Reset segment control
-(void)resetSegment {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					[self slideContactOut];
				}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactsViewController class]]) {
					ContactsViewController* dref = (ContactsViewController*)f1;
					[dref resetSegment];
				}
			}
			break;
		}
	}
}

// show Favorites Hover View
-(void)showFavoritesHoverView {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					[self slideFavoriteOut];
				}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactsViewController class]]) {
					ContactsViewController* dref = (ContactsViewController*)f1;
					[dref showHoverView:YES];
				}
			}
			break;
		}
	}
}

// Display Events Badge
-(void)showEventsBadge:(NSString*)badge {
	
	UINavigationController* nc;
		
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			nc.tabBarItem.badgeValue = badge;
			break;
			}
		}
}

// Display Contacts Badge
-(void)showContactsBadge:(NSString*)badge {
	
	UINavigationController* nc;
	
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			nc.tabBarItem.badgeValue = badge;
			break;
			}
		}
}

// show Events Hover View
-(void)showEventsHoverView:(BOOL)show {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					// TODO
					// Will need to slide events out, eventually
					//[self slideContactOut];
				}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[HomeViewController class]]) {
					HomeViewController* dref = (HomeViewController*)f1;
					[dref showHoverView:show];
					}
				if ([f1 isKindOfClass:[ProfileDetailViewController class]]) {
					{ProfileDetailViewController* dref = (ProfileDetailViewController*)f1;
					[dref showHoverView:show];
					}
				}
			}
			break;
		}
	}
}

// show Profile Hover View
-(void)showProfileHoverView:(BOOL)show {
	
	UINavigationController* nc;
	
	// First, if we need to, slide out
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Profile"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					// TODO
					// Will need to slide profile out, eventually
					//[self slideContactOut];
				}
			}
			break;
		}
	}
	
	// Then, show the hover view (loading...*)
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Profile"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				//if ([f1 isKindOfClass:[HomeViewController class]]) {
				//	HomeViewController* dref = (HomeViewController*)f1;
				//	[dref showHoverView:show];
				//}
				if ([f1 isKindOfClass:[ProfileDetailViewController class]]) {
					{ProfileViewController* dref = (ProfileViewController*)f1;
						[dref showHoverView:show];
					}
				}
			}
			break;
		}
	}
}

// Reload contacts table
-(void)reloadContactsTable {
	
	UINavigationController* nc;
	
	// First, slide out if we need to
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactDetailViewController class]]) {
					[self slideContactOut];
					}
				}
			break;
		}
	}
	
	// Then, reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[ContactsViewController class]]) {
					ContactsViewController* dref = (ContactsViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
				}
			}
			break;
		}
	}
}

// Reload events table
-(void)reloadEventsTable {
	
	UINavigationController* nc;
	
	// Reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[HomeViewController class]]) {
					//if ([f1 isKindOfClass:[HomeViewController class]] && (self.cliqset.mode == 14)) {
					HomeViewController* dref = (HomeViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
					[dref showHoverView:NO];
				}
				if ([f1 isKindOfClass:[ProfileDetailViewController class]]) {
					//if ([f1 isKindOfClass:[ProfileDetailViewController class]] && (self.cliqset.mode == 15)) {
					ProfileDetailViewController* dref = (ProfileDetailViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
					[dref showHoverView:NO];
				}
			}
			break;
		}
	}
}

// Reload profile events table
-(void)reloadProfileTable {
	
	UINavigationController* nc;
	
	// Reload the data
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Profile"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[HomeViewController class]]) {
					//if ([f1 isKindOfClass:[HomeViewController class]] && (self.cliqset.mode == 19)) {
					HomeViewController* dref = (HomeViewController*)f1;
				//	[dref showHoverView:YES];
				//	[dref reloadData];
					[dref showHoverView:NO];
				}
				if ([f1 isKindOfClass:[ProfileViewController class]]) {
					//if ([f1 isKindOfClass:[ProfileViewController class]] && (self.cliqset.mode == 19)) {
					ProfileViewController* dref = (ProfileViewController*)f1;
					[dref showHoverView:YES];
					[dref reloadData];
					[dref showHoverView:NO];
				}
			}
			break;
		}
	}
}

// Reload favorites table
-(void)reloadFavoritesTable {
	
	UINavigationController* nc;
	
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			for (UIViewController* f1 in nc.viewControllers) {
				if ([f1 isKindOfClass:[FavoritesViewController class]]) {
					FavoritesViewController* dref = (FavoritesViewController*)f1;
					[dref reloadData];
					}
				else {
					[self slideFavoriteOut];
				}
			}
			break;
		}
	}
}

#pragma mark Handle View Flipping Here

-(void)flipSplashToFront {
	
	self.tabBarController.view.hidden = YES;
	SplashViewController* splash = [[SplashViewController alloc] initWithNibName:@"Splash" bundle:nil];
	[self setSplashViewController:splash];
	
	[self.window addSubview:[splash view]];
	
	[splash release];
}

-(void)flipSplashToBack {
	
	self.tabBarController.view.hidden = NO;
	[splashViewController.view removeFromSuperview];
	[splashViewController release];
	splashViewController=nil;
}

-(void)flipLoginToFront {
	
	LoginViewController* aLogin = [[LoginViewController alloc] initWithNibName:@"LoginView" bundle:nil];
	[self setLoginViewController:aLogin];
	
	[self.window addSubview:[aLogin view]];
	[aLogin.f1 becomeFirstResponder];
	
	[aLogin release];
}

-(void)flipLoginToBack {
	
	[loginViewController.view removeFromSuperview];
	[loginViewController release];
	loginViewController=nil;
}

#pragma mark ---- Profile ----

-(void)addProfile:(Profile *)incomingProfile {
	self.currentProfile = [incomingProfile retain];
}

#pragma mark ---- Status ----

-(void)addStatus:(Status *)incomingStatus {
	self.currentStatus = incomingStatus.status;
}

#pragma mark ---- Contacts ----

-(void)addContact:(Contact*)contact {
	[contacts addObject:(id)contact];
}

#pragma mark ---- Events ----

-(void)addEvent:(Event*)event {
	
	// To Events
	if (event.mode == 14) {
		[toEvents addObject:(id)event];
	}
	
	// From Events
	if (event.mode == 15) {
		[fromEvents addObject:(id)event];
	}
	
	// Profiles
	if (event.mode == 19) {
		[profileEvents addObject:(id)event];
	}
}

#pragma mark ----- UITabBarController delegates ----

// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
	
	if ([viewController.title isEqualToString:@"Home"]) {
		// Clear events badge after we tab to it
		[self showEventsBadge:nil];
		}
	
	if ([viewController.title isEqualToString:@"Contacts"]) {
		// Clear contact badge after we tab to it
		[self showContactsBadge:nil];
		}
	
	// We need to logout
	if ([viewController.title isEqualToString:@"Logout"]) {
		[self logout:nil];
		self.tabBarController.selectedIndex = 0;
		}
}
	
#pragma mark ---- Favorite Detail ----

// Slide Favorite Detail Out of View
-(void)slideFavoriteOut {
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Favorite Detail Into View
-(void)slideFavoriteIn:(NSInteger)index {
	
	ContactDetailViewController* aCV = [[ContactDetailViewController alloc] initWithNibName:@"ContactDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Favorites"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index      = index;
	aCV.isFavorite = YES;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

#pragma mark ---- Contact Detail----

// Slide Add Contact Detail Into View
-(void)slideAddContactIn:(NSInteger)index {
	
	ContactDetailViewController* aCV = [[ContactDetailViewController alloc] initWithNibName:@"AddContactDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Contact Detail Out of View
-(void)slideContactOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			break;
			}
		}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Contact Detail Into View
-(void)slideContactIn:(NSInteger)index {
	
	ContactDetailViewController* aCV = [[ContactDetailViewController alloc] initWithNibName:@"ContactDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Contacts"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
		
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Profile Detail Into View
-(void)slideProfileIn:(NSInteger)index {
	
	ProfileDetailViewController* aCV = [[ProfileDetailViewController alloc] initWithNibName:@"ProfileDetailView" bundle:nil];
	
	UINavigationController* nc = nil;
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Home"]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.index = index;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Address Type Into View
-(void)slideAddressTypeIn:(EditAddressViewController*)parent {
	
	AddressTypeViewController* aCV = [[AddressTypeViewController alloc] initWithNibName:@"AddressTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Address Type Out of View
-(void)slideAddressTypeOut:(EditAddressViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
	for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.addresses reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide IM Type Into View
-(void)slideIMTypeIn:(EditIMViewController*)parent {
	
	IMTypeViewController* aCV = [[IMTypeViewController alloc] initWithNibName:@"IMTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide URL Type Into View
-(void)slideURLTypeIn:(EditURLViewController*)parent {
	
	URLTypeViewController* aCV = [[URLTypeViewController alloc] initWithNibName:@"URLTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Email Type Into View
-(void)slideEmailTypeIn:(EditEmailViewController*)parent {
	
	EmailTypeViewController* aCV = [[EmailTypeViewController alloc] initWithNibName:@"EmailTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide URL Type Out of View
-(void)slideURLTypeOut:(EditURLViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.urls reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide Email Type Out of View
-(void)slideEmailTypeOut:(EditEmailViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.emailAddresses reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide IM Type Out of View
-(void)slideIMTypeOut:(EditIMViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.ims reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide Phone Type Into View
-(void)slidePhoneTypeIn:(EditPhoneViewController*)parent {
	
	PhoneTypeViewController* aCV = [[PhoneTypeViewController alloc] initWithNibName:@"PhoneTypeView" bundle:nil];
	
	UINavigationController* nc = nil;

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent = parent;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Phone Type Out of View
-(void)slidePhoneTypeOut:(EditPhoneViewController*)parent {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[parent.phoneEdit reloadData];
	
	[nc popViewControllerAnimated:YES];
}

// Slide Address Out of View
-(void)slideAddressOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Address Edit Into View
-(void)slideAddressIn:(ContactDetailViewController*)parent label:(NSString*)label street:(NSString*)street locality:(NSString*)locality region:(NSString*)region postalCode:(NSString*)postalCode country:(NSString *)country {
	
	EditAddressViewController* aCV = [[EditAddressViewController alloc] initWithNibName:@"EditAddressView" bundle:nil];
	
	UINavigationController* nc = nil;

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent           = parent;
	aCV.addressTypeField = (NSMutableString*)[label lowercaseString];
	aCV.streetField      = (NSMutableString*)street;
	aCV.localityField    = (NSMutableString*)locality;
	aCV.regionField      = (NSMutableString*)region;
	aCV.postalCodeField  = (NSMutableString*)postalCode;
	aCV.countryField     = (NSMutableString*)country;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide URL Edit Into View
-(void)slideURLIn:(ContactDetailViewController*)parent label:(NSString*)label content:(NSString*)content {
	
	EditURLViewController* aCV = [[EditURLViewController alloc] initWithNibName:@"EditURLView" bundle:nil];
	
	UINavigationController* nc = nil;

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent       = parent;
	aCV.urlTypeField = (NSMutableString*)[label lowercaseString];
	aCV.urlField     = (NSMutableString*)content;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide User Edit Into View
-(void)slideUserIn:(ContactDetailViewController*)parent givenName:(NSString*)givenName familyName:(NSString*)familyName position:(NSString*)position company:(NSString*)company {
	
	EditUserViewController* aCV = [[EditUserViewController alloc] initWithNibName:@"EditUser" bundle:nil];
	
	UINavigationController* nc = nil;
	
	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent          = parent;
	aCV.givenNameField  = givenName == nil ? @"" : (NSMutableString*)givenName;
	aCV.familyNameField = familyName == nil ? @"" : (NSMutableString*)familyName;
	aCV.positionField   = position == nil ? @"" : (NSMutableString*)position;
	aCV.companyField    = company == nil ? @"" : (NSMutableString*)company;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide User Out of View
-(void)slideUserOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}
	
	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	// Tell app we need to update our list views
	self.updateContactsFlag  = YES;
	self.updateFavoritesFlag = YES;
	self.reloadListView      = YES;
	
	[nc popViewControllerAnimated:YES];
}

// Slide URL Out of View
-(void)slideURLOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide IM Edit Into View
-(void)slideIMIn:(ContactDetailViewController*)parent label:(NSString*)label content:(NSString*)content {
	
	EditIMViewController* aCV = [[EditIMViewController alloc] initWithNibName:@"EditIMView" bundle:nil];
	
	UINavigationController* nc = nil;

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent      = parent;
	aCV.imTypeField = (NSMutableString*)[label lowercaseString];
	aCV.imField     = (NSMutableString*)content;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide IM Out of View
-(void)slideIMOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Email Edit Into View
-(void)slideEmailIn:(ContactDetailViewController*)parent label:(NSString*)label content:(NSString*)content {
	
	EditEmailViewController* aCV = [[EditEmailViewController alloc] initWithNibName:@"EditEmailView" bundle:nil];
	
	UINavigationController* nc = nil;

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent           = parent;
	aCV.emailTypeField   = (NSMutableString*)[label lowercaseString];
	aCV.emailAddressField = (NSMutableString*)content;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Email Out of View
-(void)slideEmailOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Slide Phone Edit Into View
-(void)slidePhoneIn:(ContactDetailViewController*)parent label:(NSString*)label content:(NSString*)content {
	
	EditPhoneViewController* aCV = [[EditPhoneViewController alloc] initWithNibName:@"EditPhoneView" bundle:nil];
	
	UINavigationController* nc = nil;
	
	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
	
    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	aCV.parent           = parent;
	aCV.phoneTypeField   = (NSMutableString*)[label lowercaseString];
	aCV.phoneNumberField = (NSMutableString*)content;
	
	[nc pushViewController:aCV animated:YES];
	[aCV release];
}

// Slide Phone Out of View
-(void)slidePhoneOut {
	
	UINavigationController* nc = nil;
	
	if ([[self tabBarController].viewControllers count] == 1) {return;}

	NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";

    for( UIViewController* vc in [self tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:target]) {
			nc = (UINavigationController *)vc;
			break;
		}
	}
	
	if (nc == nil) {return;}
	
	[nc popViewControllerAnimated:YES];
}

// Answer confirmation that we really want to logout.
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	// Answer logout question
	if (buttonIndex == 0 && !self.isSyncing) {
		//self.cliqset.mode     = 0;
		self.isAuthenticated  = NO;
		self.isAuthenticating = YES;
		[self.cliqset logout];
		}
	
	// Answer Sync question
	if (buttonIndex == 0 && self.isSyncing) {		
		// Show busy indicator
		[self showContactsHoverView:YES];		
		// Reset contacts
		[self.contacts removeAllObjects];
		// Reset events
		// [self.events removeAllObjects];
		// Get user contacts
		[self.cliqset getUserContacts:self.userString];
		}

	self.isSyncing = NO;
}

// Logout
-(IBAction)logout:(id)id {
    UIAlertView* myAlert = [[UIAlertView alloc] initWithTitle:@"cliqset" message:@"Do You Wish to Logout?" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil];
	
	[myAlert addButtonWithTitle:@"No"];
	
    [myAlert show];
    [myAlert release];    
}


// We are checking this timer so that we may see if events or contacts need reloading.  
- (void)watchDogFired:(NSTimer *)timer
{
	NSLog(@"watchDogFired");

	// Check for new To events
	[self.cliqset loadToEvents];
	
	// Check for new contacts
	[self.cliqset getUserContacts:self.userString];
}	

// We are checking this timer so that we may readjust our viewport.  
- (void)timerFired:(NSTimer *)timer
{
	// Do we need to reload the contacts / favorites list views?
	if (reloadListView) {
		UINavigationController* nc = nil;
		
		NSString *target = self.tabBarController.selectedIndex == 3 ? @"Favorites" : @"Contacts";
		
		for( UIViewController* vc in [self tabBarController].viewControllers ) {
			NSString* testString = (NSString*)vc.title;
			if ([testString isEqualToString:target]) {
				nc = (UINavigationController *)vc;
				int count = 0;
				for (UIViewController* f1 in nc.viewControllers) {
					if (count++ > 0) return;
					//NSLog(@"%@", f1.title); 
				}
				break;
			}
		}
		
		if (nc == nil) {return;}
		
		reloadListView = NO;
		
		NSLog(@"Fired %@", target);
		
		if ([target isEqualToString:@"Contacts"]) {
			if (self.updateContactsFlag) {
				self.updateContactsFlag = NO;
				[self reloadContactsTable];
			}
		} 
		else {
			if (updateFavoritesFlag) {
				self.updateFavoritesFlag=NO;
				[self reloadFavoritesTable];
			}
		}
		
		// If we have an update still pending, then check one more time
		if (updateContactsFlag || updateFavoritesFlag) {self.reloadListView=YES;}
	}
}

-(void)resetTimer {
	[viewTimer invalidate];
	[viewTimer release];
	viewTimer = nil;
}

-(void)resetWatchDogTimer {
	[watchDogTimer invalidate];
	[watchDogTimer release];
	watchDogTimer = nil;
}

// Free up our junk
- (void)dealloc {
	[currentProfile release];
	[currentStatus release];
	[viewTimer release];
	[watchDogTimer release];
	[splashViewController release];
	[cliqset release];
	[database release];
	[profileEvents release];
	[fromEvents release];
	[toEvents release];
	[favorites release];
	[contacts release];
	[userString release];
	[authenticationString release];
	[loginString release];
	[passwordString release];
	[loginViewController release];
    [tabBarController release];
    [window release];
    [super dealloc];
}

@end

